package com.teamclub.app.sconfs.oauth

import com.teamclub.sutil.HttpContextUtils
import com.teamclub.util.libs.{Json, R}
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import javax.servlet.{ServletRequest, ServletResponse}
import org.apache.commons.lang3.StringUtils
import org.apache.http.HttpStatus
import org.apache.shiro.authc.{AuthenticationException, AuthenticationToken}
import org.apache.shiro.web.filter.authc.AuthenticatingFilter
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestMethod

class OAuth2Filter extends AuthenticatingFilter{
  val logger = LoggerFactory.getLogger(classOf[OAuth2Filter])
  override def createToken(servletRequest: ServletRequest, servletResponse: ServletResponse): AuthenticationToken = {
    val token = getRequestToken(servletRequest.asInstanceOf[HttpServletRequest])
    if(StringUtils.isBlank(token)) {
      null
    } else {
      new OAuth2Token(token)
    }
  }

  override def onAccessDenied(servletRequest: ServletRequest, servletResponse: ServletResponse): Boolean = {
    RequestMethod.OPTIONS.name == servletRequest.asInstanceOf[HttpServletRequest].getMethod
  }


  override def onAccessDenied(request: ServletRequest, response: ServletResponse, mappedValue: scala.Any): Boolean = {
    val token = getRequestToken(request.asInstanceOf[HttpServletRequest])
    if(StringUtils.isBlank(token)) {
      val httpResponse = response.asInstanceOf[HttpServletResponse]
      httpResponse.setHeader("Access-Control-Allow-Credentials", "true")
      httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin)
      val json = Json.toJson(R.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"))
      httpResponse.getWriter.print(json)
      false
    } else {
      executeLogin(request, response)
    }
  }


  override def onLoginFailure(token: AuthenticationToken, e: AuthenticationException, request: ServletRequest, response: ServletResponse): Boolean = {
    val httpResponse = response.asInstanceOf[HttpServletResponse]
    import com.teamclub.sutil.HttpContextUtils
    httpResponse.setContentType("application/json;charset=utf-8")
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true")
    httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin)
    import java.io.IOException

    import com.teamclub.util.libs.R
    import org.apache.http.HttpStatus
    try { //处理登录失败的异常
      val throwable = if (e.getCause == null) e
      else e.getCause
      val r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage)
      val json = Json.toJson(r)
      httpResponse.getWriter.print(json)
    } catch {
      case e1: IOException => {
        logger.error("", e1)
      }
    }
    false
  }

  def getRequestToken(httpRequest: HttpServletRequest): String = {
    var token = httpRequest.getHeader("token")
    if(StringUtils.isBlank(token)) {
      token = httpRequest.getParameter("token")
    }
    token
  }
}
